package sojo.com.inverter.service.Impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;
import sojo.com.inverter.modbus.ModbusClient;
import sojo.com.inverter.service.Device;
import sojo.com.inverter.service.DeviceProtocolService;
import sojo.com.inverter.service.ScheduledTaskService;
import sojo.com.inverter.task.ScheduledTask;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * @author cheng_hu
 * @description:
 * @date 2023-02-22 15:42:53
 */
@Slf4j
@Service
public class ScheduledTaskServiceImpl implements ScheduledTaskService {

    @Autowired
    @Lazy
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    @Autowired
    private Map<String, DeviceProtocolService> deviceProtocolServiceMap;

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    /**
     * 存放已经启动的任务map
     */
    private final Map<String, ScheduledFuture<?>> scheduledFutureMap = new ConcurrentHashMap<>();

    @Override
    public boolean startTask(String taskKey, ModbusClient modbusClient, Device device) {
        if (scheduledFutureMap.containsKey(taskKey)) {
            log.info("任务已启动");
            return false;
        }

        ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(new ScheduledTask(taskKey, modbusClient, device, deviceProtocolServiceMap),
                triggerContext -> new CronTrigger("0 */5 * * * ?").nextExecutionTime(triggerContext));

//        "*/5 * * * * ?"
//        ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(new ScheduledTask(taskKey, modbusClient, device, deviceProtocolServiceMap),
//                triggerContext -> new CronTrigger("*/20 * * * * ?").nextExecutionTime(triggerContext));

        scheduledFutureMap.put(taskKey, future);

        log.info("定时任务启动成功");
        return true;
    }

    @Override
    public void stopTask(String taskKey) {
        if (!scheduledFutureMap.isEmpty()) {
            for (String key : scheduledFutureMap.keySet()) {
                ScheduledFuture<?> future = scheduledFutureMap.get(key);
                if (future != null) {
                    future.cancel(true);
                    log.info("定时任务关闭成功");
                }
            }
        }
    }
}
